use super::{Data, SelectOption};
use leptos::*;
use std::{collections::HashMap, rc::Rc};

#[allow(non_snake_case)]
#[component]
pub fn Select(
    #[prop(into)] name: String,
    label: &'static str,
    #[prop(optional)] options: &'static [SelectOption],
) -> impl IntoView {
    let (getter, setter) = use_context::<(
        ReadSignal<HashMap<String, Data>>,
        WriteSignal<HashMap<String, Data>>,
    )>()
    .expect("to have found the setter provided");
    let name = Rc::new(name);
    let value = {
        let name = Rc::clone(&name);
        move || {
            let map = getter.get();
            let value = map
                .get(name.as_str())
                .and_then(|v| v.str())
                .unwrap_or_default();
            value.to_string()
        }
    };
    view! {
        <div class="flex flex-col py-2 gap-1">
        <label class="pl-2 text-lg" for={name.as_ref()}>
        {label}
        </label>
        <select value=value
        id = {name.as_ref()}
         on:change=move |ev| {
            let v = event_target_value(&ev);
            setter.update(|value| {
                let v = Data::String(v);
                let name = name.as_ref().to_string();
                value.insert(name, v);
            })
        } class="h-9 border rounded px-2 outline-blue-400 bg-transparent">
            {
                options.iter()
                .map(|v| {
                    view! {
            <option value={&v.value}>{&v.label}</option>
                    }
                })
                .collect_view()
            }
        </select>
        </div>
    }
}
